<?php

/**
 * usuario actions.
 *
 * @package    camaras
 * @subpackage usuario
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12474 2008-10-31 10:41:27Z fabien $
 */
class usuarioActions extends sfActions
{
  public function executeLogin(sfWebRequest $request)
  {
  	if (!$this->getUser()->isAuthenticated()) {

	  $this->form = new LoginForm();
	
	  if ($request->isMethod('POST'))
	  {
		$this->form->bind($request->getParameter('login'));
		 
		if ($this->form->isValid()) 
		{
	      //echo "<br>É válido";
		  $arr_login = $_POST['login'];
		  $usr = ($arr_login['email']);
		  $pwd = ($arr_login['senha']);
				  
		  //echo "<BR>usr: ".$usr."<br>pwd: ".$pwd."<br>pwd md5: ".md5($pwd);
			
		  $q = Doctrine_Query::create()
			->from('Usuario u')
			->andWhere('no_email = ?', $usr)
			->andWhere('co_senha = ?', $pwd);
			
		  $results = $q->execute();
			
		  $this->usuario = Doctrine::getTable('Usuario')->find(array($results[0]['cd_usuario']));
			
		  if (is_object($this->usuario)) {
			  
			foreach ($results as $usuario) {
				
			  //atualiza dt_ultimo_acesso 
			  $q = Doctrine_Query::create()
				->update('Usuario u')
				->set('u.dt_ultimo_acesso', '?', date("Y.m.d H:i:s",time()))
				->where('u.cd_usuario = ?', $usuario->getCdUsuario())
				->execute();
				
			  if ($usuario->getDeleted()) {
			  
				$this->getUser()->setFlash('error', 'Usuário desligado do sistema!');

			  } else {

			    $this->getUser()->setAuthenticated(true);
				$this->getUser()->setAttribute('nome', $usuario->getName(), 'usr');
				$this->getUser()->setAttribute('email', $usuario->getNoEmail(), 'usr');
				$this->getUser()->setAttribute('reset_senha', $usuario->getResetSenha(), 'usr');
				$this->getUser()->setAttribute('cd_usuario', $usuario->getCdUsuario(), 'usr');
				$this->getUser()->setAttribute('gerente', ($usuario->getTipoUsuario() == 'Gerente') ? true : false, 'usr');

				//carrega datas para calendário lateral
				//replicado na calendário/index e usuario/login
				$qe = Doctrine_Query::create()
				->from('Evento e')
				->addWhere('deleted = ?', 0)
				->addWhere('dt_hr_termino >= ?',date("Y-m-01",time()))
				->orderBy('dt_hr_inicio')
				;

				$eventos = $qe->execute();

				foreach ($eventos as $i => $data) {
					if ( (date('d-m-Y' ,strtotime($data->dt_hr_inicio)) == date('d-m-Y' ,strtotime($data->dt_hr_termino))) ) {
					  $datas_eventos[] = $data->dt_hr_inicio;
					} else {
					  $dt_tmp = $data->dt_hr_inicio;
					  //trata eventos c/+ de 1 dia
					  while($dt_tmp < $data->dt_hr_termino) {
						//limita as datas em 3 meses começando no 1º dia do mês corrente
						if (strtotime($dt_tmp) >= strtotime(date('01-m-Y',time())) && strtotime($dt_tmp) < strtotime(date('01-m-Y',time()).' + 3 months')) {
						  $datas_eventos[] = $dt_tmp;
						}
						$dt_tmp = date('Y-m-d',strtotime($dt_tmp.' + 1 days'));
					  }
					}
				}
				$this->getUser()->setAttribute('data', $datas_eventos, 'eventos');

				//Reset Senha
				if ($usuario->getResetSenha()) {
				  $this->getUser()->setFlash('notice', 'atualize sua senha');
				  $this->form = new ResetSenhaForm();
				  $this->redirect('usuario/resetSenha');			  	
				} else {
				  $this->redirect('@homepage');			  	
				}
			  }

			}
			
		  } else {
		    $this->getUser()->setFlash('error', 'E-mail ou senha inválida. Tente de novo!');
		  }
	    }
	  }
	} else {
	  $this->redirect('@homepage');
  	}
  }
  
  public function executeLogout()
  {
	$this->getUser()->getAttributeHolder()->removeNamespace('camara');
	$this->getUser()->getAttributeHolder()->removeNamespace('eventos');
	$this->getUser()->getAttributeHolder()->removeNamespace('usr');
	$this->getUser()->setAuthenticated(false);
    $this->redirect('usuario/login');	
  }
    
  public function executeResetSenha(sfWebRequest $request)
  {

  	if ($this->getUser()->getAttribute('reset_senha',null,'usr')) {

	  $this->form = new ResetSenhaForm();
	  
	  if ($request->isMethod('POST'))
	  {
		$this->form->bind($request->getParameter('reset'));
		 
		if ($this->form->isValid()) 
		{ 
	      //echo "<br>É válido";
		  $arr_reset = $_POST['reset'];
		  $pw_atual = ($arr_reset['senha_atual']);
		  $pw_nova = ($arr_reset['nova_senha']);
		  $pw_nova_repit = ($arr_reset['repita_nova_senha']);
			
		  $q = Doctrine_Query::create()
			->from('Usuario u')
			->where('no_email = ?', $this->getUser()->getAttribute('email',null,'usr'))
			->andWhere('co_senha = ?', $pw_atual);
			
		  $results = $q->execute();
			
		  $this->usuario = Doctrine::getTable('Usuario')->find(array($results[0]['cd_usuario']));
			
		  if (is_object($this->usuario)) {
			  
			if ($pw_nova == $pw_nova_repit) {
			  if ($pw_nova <> $pw_atual) { 
			  	foreach ($results as $usuario) {
			      //atualiza senha
				  $q = Doctrine_Query::create()
					->update('Usuario u')
					->set('u.co_senha', '?', $pw_nova)
					->set('u.reset_senha', '?', 0)
					->where('u.cd_usuario = ?', $usuario->getCdUsuario())
					->execute();
					
				  $this->getUser()->setAttribute('reset_senha', false, 'usr');
		          $this->redirect('@homepage');
			    }
			  } else { $this->getUser()->setFlash('error', 'A nova senha não pode ser igual a anterior. Tente de novo!');
			  }
			} else { $this->getUser()->setFlash('error', 'A nova senha não confere com a repetição. Tente de novo!');
			}
		  } else { $this->getUser()->setFlash('error', 'Senha inválida. Tente de novo!');
		  }
		  
	    }
	  }
	} else { $this->redirect('@homepage');
  	}
  }
  
  public function executeIndex(sfWebRequest $request)
  {
    $this->usuario_list = Doctrine::getTable('Usuario')
      ->createQuery('a')
	  ->where('deleted = 0')
	  ->andwhere('name <> ?', 'Admin')
	  ->orderBy('cd_tipo_usuario, name')
    ;
		  
    $this->pager = new sfDoctrinePager(
		'Usuario',
		sfConfig::get('app_qtd_registros_por_pagina')
	);
		
	$this->pager->setPage($request->getParameter('page', 1));
    $this->pager->setQuery($this->usuario_list);
	$this->pager->init();
	
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->usuario = Doctrine::getTable('Usuario')->find(array($request->getParameter('cd_usuario')));
    $this->forward404Unless($this->usuario);
  }

  public function executeNew(sfWebRequest $request)
  {
	if(!$this->getUser()->getAttribute('gerente',null,'usr')){
	  $this->getUser()->setFlash('error', sfConfig::get('app_msg_cadastro_exclusivo_gerente'));
	  $this->redirect('@homepage');
	} else {
      $this->form = new UsuarioForm();
	}
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod('post'));

    $this->form = new UsuarioForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($usuario = Doctrine::getTable('Usuario')->find(array($request->getParameter('cd_usuario'))), sprintf('Object usuario does not exist (%s).', array($request->getParameter('cd_usuario'))));
    $this->form = new UsuarioForm($usuario);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod('post') || $request->isMethod('put'));
    $this->forward404Unless($usuario = Doctrine::getTable('Usuario')->find(array($request->getParameter('cd_usuario'))), sprintf('Object usuario does not exist (%s).', array($request->getParameter('cd_usuario'))));
    $this->form = new UsuarioForm($usuario);

    $this->processForm($request, $this->form);

    $this->setTemplate('index');
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($usuario = Doctrine::getTable('Usuario')->find(array($request->getParameter('cd_usuario'))), sprintf('Object usuario does not exist (%s).', array($request->getParameter('cd_usuario'))));
    $usuario->delete();

    $this->getUser()->setFlash('notice', sfConfig::get('app_msg_confirmacao'));			
    $this->redirect('usuario/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()));
    if ($form->isValid())
    {
      $usuario = $form->save();

      $this->getUser()->setFlash('notice', sfConfig::get('app_msg_confirmacao'));			
      $this->redirect('usuario/index');
    }
  }
}
